#include <stdlib.h>
#include <stdio.h>
#include <time.h>

#define _SDL_main_h
#include <SDL/SDL.h>
#include <SDL/SDL_ttf.h>
#include "main_sdl.h"

/** \brief Le "main" SDL : initialise le jeu et contient la boucle de jeu
 *
 * \return int
 *
 */
int mainSDL()
{
    srand(time(NULL));

    int continuer = 1, boolBars = 1, i, k;
    SDL_Surface *screen = NULL;
    SDL_Event event;
    TTF_Font *font = NULL;

    freight BDD_freight[10];
    spaceShip BDD_spaceShip[10];

   /*----------------------------
    creation des variables de jeu
    -----------------------------*/
    player mainPlayer;
    memset(mainPlayer.name, 0, sizeof(mainPlayer.name)); /* permet d'initialiser le nom du joueur, ainsi rien n'est affiche au debut lors de SDL_initPlayer */

    spaceShip sPlayer, spaceShipTemp;

    factory factoryTemp;

    explosion expl, explLaser;
    expl.boolExplosion      = 0;
    expl.etape              = 0;
    explLaser.boolExplosion = 0;
    explLaser.etape         = 0;

    /* =====================
       Initialisation de SDL
       ===================== */
    if (SDL_Init(SDL_INIT_VIDEO) == -1)
    {
        fprintf(stderr, "Erreur d'initialisation de la SDL : %s\n", SDL_GetError());
        exit(EXIT_FAILURE);
    }

    screen = SDL_SetVideoMode(800, 600, 32, SDL_HWSURFACE | SDL_DOUBLEBUF);
    if (screen == NULL) //SetVideoMode renvoie NULL si l'allocation a echouee
    {
        fprintf(stderr, "Erreur d'initialisation de la video... %s\n", SDL_GetError());
        exit(EXIT_FAILURE); //Quitte le programme
    }

    /* Images */
    SDL_Surface *playerShip=NULL, *sectorShip=NULL, *friendShip=NULL, *sectorFactory=NULL, *pirateShip=NULL, *target=NULL, *gate=NULL, *background=NULL;
    playerShip       = SDL_LoadBMP("data/playerShip.bmp");
    SDL_SetColorKey(playerShip,  SDL_SRCCOLORKEY, SDL_MapRGB(playerShip->format, 0, 0, 0));
    friendShip       = SDL_LoadBMP("data/friendShip.bmp");
    SDL_SetColorKey(friendShip,  SDL_SRCCOLORKEY, SDL_MapRGB(friendShip->format, 0, 0, 0));
    sectorShip       = SDL_LoadBMP("data/sectorShip.bmp");
    SDL_SetColorKey(sectorShip,  SDL_SRCCOLORKEY, SDL_MapRGB(sectorShip->format, 0, 0, 0));
    sectorFactory    = SDL_LoadBMP("data/sectorFactory.bmp");
    SDL_SetColorKey(sectorFactory,  SDL_SRCCOLORKEY, SDL_MapRGB(sectorFactory->format, 255, 255, 255));
    pirateShip       = SDL_LoadBMP("data/pirateShip.bmp");
    SDL_SetColorKey(pirateShip,  SDL_SRCCOLORKEY, SDL_MapRGB(pirateShip->format, 0, 0, 0));
    target           = SDL_LoadBMP("data/target.bmp");
    SDL_SetColorKey(target,  SDL_SRCCOLORKEY, SDL_MapRGB(target->format, 0, 0, 0));
    gate             = SDL_LoadBMP("data/gate.bmp");
    SDL_SetColorKey(gate,  SDL_SRCCOLORKEY, SDL_MapRGB(gate->format, 0, 0, 0));

    background       = SDL_LoadBMP("data/background.bmp");

    SDL_Surface *laserImg=NULL;
    laserImg = SDL_LoadBMP("data/laser.bmp");
    SDL_SetColorKey(laserImg,  SDL_SRCCOLORKEY, SDL_MapRGB(laserImg->format, 0, 0, 0));


    /* ========================= */
    /* Initialisation de SDL_ttf */
    /* ========================= */
    if(TTF_Init() == -1)
    {
        fprintf(stderr, "Erreur d'initialisation de TTF_Init : %s\n", TTF_GetError());
        exit(EXIT_FAILURE);
    }
    font = TTF_OpenFont("data/starcraft.ttf", 18); /* on choisit la police d'ecriture */

    SDL_WM_SetCaption("Space-Pogo", NULL);  /* titre la fenetre */

    /* ===================== */
    /* Initialisation du jeu */
    /* ===================== */
    sector* tabSector[9];
    for(i=0; i<9; i++)
    {
        tabSector[i] = NULL;
    }

    tabSector[0] = createSector();
    SDL_InitPlayer(screen, font, &mainPlayer);

    initGame(tabSector[0], &mainPlayer, &sPlayer, BDD_freight, BDD_spaceShip);

    SDL_ShowBeginMenu(screen, font, &mainPlayer, tabSector[0], &sPlayer, BDD_freight, BDD_spaceShip);

    /* ===================== */
    /*       Boucle SDL      */
    /* ===================== */
    while (continuer)
    {
        SDL_PollEvent(&event);
        switch(event.type) /* test du type d'evenement*/
        {
         /* ============================
            permet de quitter la fenetre
            ============================ */
            case SDL_QUIT:
                continuer = 0;
                break;
            /*  =================================
                on gere les touches de mouvements
                ================================= */
            case SDL_KEYDOWN:
                switch(event.key.keysym.sym)
                {
                    case SDLK_UP:
                        if((mainPlayer.controlledSpaceShip->vectorY) > (mainPlayer.controlledSpaceShip->vectorYmin))
                        {
                            mainPlayer.controlledSpaceShip->vectorY --;
                        }
                        break;
                    case SDLK_DOWN:
                         if((mainPlayer.controlledSpaceShip->vectorY) < (mainPlayer.controlledSpaceShip->vectorYmax))
                        {
                            mainPlayer.controlledSpaceShip->vectorY ++;
                        }
                        break;
                    case SDLK_LEFT:
                        if((mainPlayer.controlledSpaceShip->vectorX) > (mainPlayer.controlledSpaceShip->vectorXmin))
                        {
                            mainPlayer.controlledSpaceShip->vectorX --;
                        }
                        break;
                    case SDLK_RIGHT:
                        if((mainPlayer.controlledSpaceShip->vectorX) < (mainPlayer.controlledSpaceShip->vectorXmax))
                        {
                            mainPlayer.controlledSpaceShip->vectorX ++;
                        }
                        break;

                    case SDLK_SPACE:
                        if((mainPlayer.controlledSpaceShip->vectorX) > 0)
                        {
                            mainPlayer.controlledSpaceShip->vectorX --;
                        }
                        else if((mainPlayer.controlledSpaceShip->vectorX) < 0)
                        {
                            mainPlayer.controlledSpaceShip->vectorX ++;
                        }

                        if((mainPlayer.controlledSpaceShip->vectorY) > 0)
                        {
                            mainPlayer.controlledSpaceShip->vectorY --;
                        }
                        else if ((mainPlayer.controlledSpaceShip->vectorY) < 0)
                        {
                            mainPlayer.controlledSpaceShip->vectorY ++;
                        }
                        break;

                    case SDLK_LCTRL:
                        event.type = 0;
                        ajouterElementTabDynLaser(tabSector[mainPlayer.controlledSpaceShip->numSector]->tabLaserSector, fireLaser(*(mainPlayer.controlledSpaceShip)));
                        break;
                    case SDLK_u:
                        event.type = 0; /*evite que la touche ne soit compte plusieurs fois */
                        SDL_showPlayerInfo(screen, font, &mainPlayer);
                        break;
                    case SDLK_i:
                        event.type = 0;
                        SDL_ShowSpaceShipInventory(screen, font, *(mainPlayer.controlledSpaceShip));
                        break;
                    case SDLK_h:
                        event.type = 0;
                        SDL_gameHelp(screen, font);
                        break;
                    case SDLK_TAB:
                        event.type = 0;
                        if(boolBars == 1)
                        boolBars = 0;
                        else
                        boolBars = 1;
                        break;
                    case SDLK_s:
                        event.type = 0;
                        saveGame(mainPlayer, *(tabSector[mainPlayer.controlledSpaceShip->numSector]));
                        break;
                    case SDLK_l:
                        event.type = 0;
                        loadGame(&mainPlayer, tabSector[mainPlayer.controlledSpaceShip->numSector], BDD_freight, BDD_spaceShip);
                        break;
                    case SDLK_p:
                        continuer = 0;
                        break;
                    default:
                        break;
                }
                break;
        /* ===========================
                on gere la souris
           =========================== */
            case SDL_MOUSEBUTTONUP:
            /*  =====================================
                gestion du clic sur un vaisseau allie
                ===================================== */
                if(returnPlayerSpaceShip(mainPlayer, event.button.x, event.button.y) != NULL) /* si on a clique sur un vaisseau du joueur */
                {
                    spaceShipTemp = *(returnPlayerSpaceShip(mainPlayer, event.button.x, event.button.y)); /* pas necessaire mais les if suivants sont plus lisibles avec */
                    if(mainPlayer.controlledSpaceShip->numSector == spaceShipTemp.numSector) /* si le joueur et le vaisseau sont dans le meme secteur */
                    {
                        SDL_OnAllyClick(&mainPlayer, returnPlayerSpaceShip(mainPlayer, event.button.x, event.button.y), screen, font);
                        /*changeSpaceShip(&mainPlayer, returnPlayerSpaceShip(mainPlayer, event.button.x, event.button.y));*/ /* on change de vaisseau */
                    }
                }
            /*  ===============================
                gestion du clic sur une factory
                =============================== */
                else if(returnFactory(*(tabSector[mainPlayer.controlledSpaceShip->numSector]), event.button.x, event.button.y) != NULL) /* si on a clique sur une factory */
                {
                    factoryTemp = *(returnFactory(*(tabSector[mainPlayer.controlledSpaceShip->numSector]), event.button.x, event.button.y));
                    if(distance(mainPlayer.controlledSpaceShip->posX + 20, mainPlayer.controlledSpaceShip->posY + 20, factoryTemp.posX + 30, factoryTemp.posY + 30) <= 80) /* et qu'on est proche */
                    {
                        k = SDL_SelectTask(screen, font, &mainPlayer);
                        if(k  == 0)
                        {
                            SDL_Mission(screen, font, &mainPlayer);
                        }
                        else if(k == 1)
                        {
                            SDL_Trade(screen, font, &mainPlayer, returnFactory(*(tabSector[mainPlayer.controlledSpaceShip->numSector]), event.button.x, event.button.y)); /* on peut commercer avec */
                        }
                    }
                    else
                    {
                        if(factoryTemp.factoryKind == garage)
                            SDL_ShowFactorySpaceShip(screen, font, factoryTemp);
                        else
                            SDL_ShowFactoryInventory(screen, font, factoryTemp); /*si on est trop loin on affiche l'inventaire de la factory */

                        SDL_Pause();
                    }
                }
                event.type = 0; /*evite que la touche ne soit compte plusieurs fois */
                break;
            }
        SDL_FillRect(screen, NULL, SDL_MapRGB(screen->format, 0, 0, 0));

        SDL_ShowSector(screen, *(tabSector[mainPlayer.controlledSpaceShip->numSector]), mainPlayer, boolBars, playerShip, friendShip, sectorFactory, sectorShip, pirateShip, target, gate, background);

        sectorIA(tabSector[mainPlayer.controlledSpaceShip->numSector], mainPlayer, screen);

        playerMove(&mainPlayer);

        setShipPos(mainPlayer.controlledSpaceShip, mainPlayer.controlledSpaceShip->posX, mainPlayer.controlledSpaceShip->posY);
        updateSectorLaser(tabSector[mainPlayer.controlledSpaceShip->numSector]);

        destroySpaceShipSector(tabSector[mainPlayer.controlledSpaceShip->numSector], &mainPlayer, &expl);

        if(mainPlayer.onMission == 0)
        {
            if(tabSector[mainPlayer.numSectorMission] != NULL)
            {
                updateMission(&mainPlayer, tabSector[mainPlayer.numSectorMission]);
            }
        }

        regenShieldSpaceShipSector(tabSector[mainPlayer.controlledSpaceShip->numSector]);
        regenShieldSpaceShip(mainPlayer.controlledSpaceShip);

        /*hotSpotSector(&mainSector, screen);*/

        collisionGlobal(tabSector[mainPlayer.controlledSpaceShip->numSector], &mainPlayer, &explLaser);
        printSectorLaser(screen, laserImg, *(tabSector[mainPlayer.controlledSpaceShip->numSector]));

        starGate(screen, gate, mainPlayer.controlledSpaceShip, &tabSector, BDD_freight, BDD_spaceShip);

        if(expl.boolExplosion == 1)
        {
            printExplosionSpaceShip(screen, &expl);
        }
        if(explLaser.boolExplosion == 1)
        {
            printExplosionLaser(screen, &explLaser);
        }

        if(mainPlayer.controlledSpaceShip->hullCURRENT < 0)
        {
            continuer = 0;
        }

        SDL_Flip(screen);
        SDL_Delay(25);
    }

    if(mainPlayer.controlledSpaceShip->hullCURRENT<0)
    {
       SDL_ShowGameOver(screen, font);
    }

    /*freeSpaceShipSector(&mainSector);
    freeFactorySector(&mainSector);*/

    for(i=0; i<9; i++)
    {
        if(tabSector[i] != NULL)
        {
            freeSectorTDLaser(tabSector[i]);
            freeSector(tabSector[i]);
        }
    }

    /*freeSpaceShipPlayer(&mainPlayer);*/

    SDL_FreeSurface(playerShip);
    SDL_FreeSurface(friendShip);
    SDL_FreeSurface(sectorFactory);
    SDL_FreeSurface(sectorShip);
    SDL_FreeSurface(pirateShip);
    SDL_FreeSurface(target);
    SDL_FreeSurface(gate);
    SDL_FreeSurface(laserImg);
    SDL_FreeSurface(background);

    TTF_CloseFont(font);

    TTF_Quit();
    SDL_Quit();

    return EXIT_SUCCESS;
}
